package Fragment;
import Dialog.CatSelectPicPopupWindow;
import Dialog.Cat_Detial_Dialog;
import Dialog.Cat_adopt_Dialog;
import Dialog.ClothesDonationSelectPicPopupWindow;
import Dialog.Clothes_Donation_Detial_Dialog;
import Dialog.Clothes_donation_donate_Dialog;
import Dialog.Library_Detial_Dialog;
import Dialog.Library_Detial_Dialog;
import Dialog.Register_Dialog;
import Dialog.SelectPicPopupWindow;
import Entities.CatWitness;
import Entities.Clothes;
import Entities.ClothesDonation;
import Entities.ClothesDonationList;
import Test.Test;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.text.Layout;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import Entities.Library;
import MapUtils.MapUtils;
import Preferences.Preferences;
import Preferences.Preferences;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.example.zelonghu.testgps.AppContent;
import com.example.zelonghu.testgps.LocationUtils;
import com.example.zelonghu.testgps.NavigationHost;
import com.example.zelonghu.testgps.R;
import SQLUtils.sqllite;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import static android.content.Context.INPUT_METHOD_SERVICE;

/**
 * @author zelonghu QQ:1032006226
 * @name testGPS2
 * @class name：Fragment
 * @class describe
 * @time 2019/5/28 4:05 PM
 * @change
 * @chang time
 * @class describe
 */
public class MainFragment extends Fragment implements View.OnClickListener, AMapLocationListener ,AMap.OnMarkerClickListener{
    AMap aMap = null;
    Button me_profile_button;
    TextView textView = null;
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    private String[] strMsg;//接收收到的信息
    private Button me_locationbutton = null;
    private Button findhelpbutton = null;
    private LatLng nowPos = null;
    List<Library> ll = null;//图书馆的list
    List<CatWitness> cl = null;//流浪猫的list
    List<ClothesDonation> cdl = null;//捐衣活动的list；
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {

        //todo 首先进行创建表操作，不论其成功与否，都会保证用数的时候会有数
        //sqllite.droptable(sqllite.getDB(getContext()),AppContent.cat_register_list_tablename);
        //sqllite.droptable(sqllite.getDB(getContext()),AppContent.library_register_list_tablename);
        //sqllite.droptable(sqllite.getDB(getContext()),AppContent.clothes_donatioin_list_tablename);

        sqllite.createLibraryRegisterListTable(sqllite.getDB(getContext()));
        sqllite.createCatAdoptListTable(sqllite.getDB(getContext()));
        sqllite.create_ClothesDonation_ListTable(sqllite.getDB(getContext()));
        super.onCreate(savedInstanceState);
    }
    //定位监听器，重写AMapListener的成员方法
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (null != aMapLocation) {
            Message msg = mHandler.obtainMessage();
            msg.obj = aMapLocation;
            msg.what = LocationUtils.MSG_LOCATION_FINISH;
            mHandler.sendMessage(msg);
        }
    }
    //定义一个Handler来处理接收到的定位成功后定位信息
    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        public void dispatchMessage(android.os.Message msg) {
            switch (msg.what) {
                //定位完成
                case LocationUtils.MSG_LOCATION_FINISH:
                    String result = "";
                    try {
                        AMapLocation loc = (AMapLocation) msg.obj;
                        result = LocationUtils.getLocationStr(loc, 1);
                        //System.out.println(result);
                        strMsg = result.split(",");
                        //Toast.makeText(MainActivity.this, "定位成功", Toast.LENGTH_LONG).show();
                        Log.d("location","定位结果是："+result);
                        Toast.makeText(getContext(), "定位成功，获取位置：" + result, Toast.LENGTH_LONG).show();
                        //textView.setText("地址：" + strMsg[0] + "\n" + "经    度：" + strMsg[1] + "\n" + "纬    度：" + strMsg[1]);

                        //获取新的地址
                        nowPos = new LatLng(Double.parseDouble(strMsg[2]), Double.parseDouble(strMsg[1]));
                        //定义所在点并指向其位置。
                        Marker marker = aMap.addMarker(new MarkerOptions().position(nowPos).title(AppContent.yourlocation).snippet(""));
                        View markerView = getActivity().getLayoutInflater().inflate(R.layout.me_markerlayout,null);
                        marker.setIcon(BitmapDescriptorFactory.fromView(markerView));



                        //设置用户图标

                        //获取login的bundle
                        Bundle bundle = new Preferences(getContext()).get_login_info();
                        String stringpath = bundle.getString("imagepath");
                        if(stringpath.length()!=0){
                            //如果存在用户头像path，那么进行设置

                        }else{
                            //使用默认图像
                        }

                        //定义图框
                        CameraUpdate mCameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(Double.parseDouble(strMsg[2]), Double.parseDouble(strMsg[1])),8,0,0));
                        aMap.moveCamera(mCameraUpdate);

                    } catch (Exception e) {
                        Toast.makeText(getContext(), "定位失败.请检查权限或网络", Toast.LENGTH_LONG).show();
                    }
                    break;
                default:
                    break;
            }
        };

    };

    /**
     * @name MainFragment
     * @class name：MainFragment
     * @author zelonghu
     * @time 2019/6/26 8:57 AM
     * @change
     * @chang time
     * @class 用于更新目前的View
     */
    class UpdateViewThread extends Thread{
        @Override
        public void run() {
            //通过网络获取所需要点的集合

            try{//模仿时间延迟
                Thread.sleep(2000);
            }catch (Exception e){
                e.printStackTrace();
            }

             ll = Test.get_library_info_fromtest();

            //画点
            //todo 绘制图书馆
            for(Library l:ll){
                MapUtils.drawLibrary(aMap,Double.parseDouble(l.getLLatitude()),Double.parseDouble(l.getLLongtitude()),
                        getActivity(),AppContent.libaray,l.getLDescription());//画点示例
            }
            //todo 绘制捐衣
            cdl = Test.get_Clothes_donation_fromtest();
            for(ClothesDonation cd:cdl){
                MapUtils.drawClothes(aMap,cd.getLatitude(),cd.getLongtitude(),getActivity()
                        , AppContent.clothes,cd.getCDDescription());
            }
            //todo 绘制流浪猫
            cl = Test.get_catwitness_info_fromtest();
            for(CatWitness c:cl){
                MapUtils.deawCatWitness(aMap,c.getLatitude(),c.getLongtitude(),
                        getActivity(),AppContent.cat,c.getCattype());
            }


            //MapUtils.drawLibrary(aMap,40.1,119,getContext(),"secondtitle","second");//画点示例
            super.run();
        }
    }



    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.testgps2_fragment_main,container,false);
        MapView mapView = (MapView) view.findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        aMap = mapView.getMap();
        aMap.setOnMarkerClickListener(this);


        Log.d("map","map启动成功");
        me_locationbutton = view.findViewById(R.id.meButton);
        me_locationbutton.setOnClickListener(this);
        findhelpbutton = view.findViewById(R.id.findhelpButton);
        findhelpbutton.setOnClickListener(this);
        me_profile_button = (Button)view.findViewById(R.id.me_profile_Button);
        me_profile_button.setOnClickListener(this);
        //定位一次
        Locate();

        //开启更新view线程
        UpdateViewThread updateViewThread = new UpdateViewThread();
        updateViewThread.start();

        return view;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.me_profile_Button:
                ((NavigationHost)getActivity()).navigateTo(new MeFragment(),true
                );
                break;
            case R.id.meButton:
                Locate();
                break;
            case R.id.findhelpButton:
                break;

        }
    }

    /**
     * @author zelonghu
     * @time 2019/6/25  2:26 PM
    * @describe 定位方法，点击一次刷新一次位置，mHandler接受定位结果。
     */
    public  void Locate(){
        // TODO Auto-generated method stub
        try {
            locationClient = new AMapLocationClient(getContext());
            locationOption = new AMapLocationClientOption();
            // 设置定位模式为低功耗模式
            locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
            // 设置定位监听
            locationClient.setLocationListener(this);
            locationOption.setOnceLocation(true);//设置为单次定位
            locationClient.setLocationOption(locationOption);// 设置定位参数
            // 启动定位
            locationClient.startLocation();
            mHandler.sendEmptyMessage(LocationUtils.MSG_LOCATION_START);
        } catch (Exception e) {
            Toast.makeText(getContext(), "定位失败", Toast.LENGTH_LONG).show();
        }
    }


    /**
     * @author zelonghu
     * @time 2019/6/28  10:22 AM
     * @describe markerclicklistenrer 用于接受marker的点击方法
     */
    @Override
    public boolean onMarkerClick(final Marker marker) {
        final Marker upmarker = marker;
        //todo 承接点击的Dialog
        View.OnClickListener dialoglistener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()){
                    case R.id.btn_rigister:
                        //todo 点击了注册/领养标点
                        switch (upmarker.getTitle()){
                            case AppContent.yourlocation:
                                //todo 如果是我的位置点击了Register
//


                                break;
                            case AppContent.libaray:
                                //todo 在library中点击了Register
                                Register_Dialog infoDialog = null;
                                //传入坐标和图书馆名称
                                infoDialog = new Register_Dialog.Builder(getContext())
                                       .setLatitude(upmarker.getPosition().latitude)
                                        .setLongtitude(upmarker.getPosition().longitude)
                                        .setLibraryName(upmarker.getSnippet()).create();

                                infoDialog.show();
                                Window window = infoDialog.getWindow();
                                //如果你是圆角之类的话，这句设置背景透明要加上。
                                //否则有个白底在那儿，你的dialog也是白色的话是看不到圆角的
                                window.setBackgroundDrawableResource(android.R.color.transparent);
                                break;
                            case AppContent.cat:
                                //todo 在流浪猫中点击了领养
                                //首先找到这个cat的实例对象
                                Double mlatitude = marker.getPosition().latitude;
                                Double mlongtitude = marker.getPosition().longitude;
                                for(CatWitness c:cl){
                                    //匹配坐标点
                                    if((c.getLatitude()+"").substring(0,7).equals((mlatitude+"").substring(0,7)) &&
                                            (c.getLongtitude()+"").substring(0,7).equals((mlongtitude+"").substring(0,7))){
                                        //匹配成功，得到library对象
                                        //弹出窗口
                                        Cat_adopt_Dialog dialog = new Cat_adopt_Dialog.Builder(getContext(),c).
                                                setLatitude(mlatitude).setLongtitude(mlongtitude).create();
                                        dialog.show();
                                        window = dialog.getWindow();
                                        //如果你是圆角之类的话，这句设置背景透明要加上。
                                        //否则有个白底在那儿，你的dialog也是白色的话是看不到圆角的
                                        window.setBackgroundDrawableResource(android.R.color.transparent);
                                    }
                                }
                                break;
                            case AppContent.clothes:
                                //todo 在捐衣活动中点击了捐献
                                //首先找到这个cat的实例对象
                                 mlatitude = marker.getPosition().latitude;
                                 mlongtitude = marker.getPosition().longitude;
                                 for(ClothesDonation cd:cdl){
                                     //匹配坐标点
                                     if((cd.getLatitude()+"").substring(0,7).equals((mlatitude+"").substring(0,7)) &&
                                             (cd.getLongtitude()+"").substring(0,7).equals((mlongtitude+"").substring(0,7))) {
                                        //匹配成功
                                         //显示窗口
                                         Clothes_donation_donate_Dialog dialog = new Clothes_donation_donate_Dialog
                                                 .Builder(getContext(),cd).setLatitude(mlatitude).setLongtitude(mlongtitude)
                                                 .create();
                                         dialog.show();
                                         window = dialog.getWindow();
                                         //如果你是圆角之类的话，这句设置背景透明要加上。
                                         //否则有个白底在那儿，你的dialog也是白色的话是看不到圆角的
                                         window.setBackgroundDrawableResource(android.R.color.transparent);
                                     }

                                     }
                                break;
                                default:
                                    //todo 如果是在其他点点击了register
                                    infoDialog = null;
                                    infoDialog = new Register_Dialog.Builder(getContext()).create();
                                    infoDialog.show();
                                    window = infoDialog.getWindow();
                                    //如果你是圆角之类的话，这句设置背景透明要加上。
                                    //否则有个白底在那儿，你的dialog也是白色的话是看不到圆角的
                                    window.setBackgroundDrawableResource(android.R.color.transparent);

                                    break;


                        }
                        break;
                    case R.id.btn_detial:

                        //todo 点击了细节标点
                        switch (upmarker.getTitle()){
                            case AppContent.libaray:
                                //todo 点击了library的marker
                                //对经纬度进行比对
                                Double mlatitude = marker.getPosition().latitude;
                                Double mlongtitude = marker.getPosition().longitude;
                                for(Library l:ll){

                                    //这里发现l.getLlatitude 的精度很高，而maker中的精度很低，所以需要进行模糊对比，取前8个点比对
                                    if(l.getLLatitude().substring(0,7).equals((mlatitude+"").substring(0,7)) &&
                                            l.getLLongtitude().substring(0,7).equals((mlongtitude+"").substring(0,7))){
                                        //匹配成功,得到点击的library对象
                                        //创建Dilog
                                        Library_Detial_Dialog dialog = new Library_Detial_Dialog.Builder(getContext())
                                                .setdescribe(l.getLDescription())
                                                .setlbookcount(l.getBookCount()).setlname(l.getLName())
                                                .setphone(l.getLPhone()).setwebsite(l.getLWebsite()).create();
                                        dialog.show();
                                        Window window = dialog.getWindow();
                                        //如果你是圆角之类的话，这句设置背景透明要加上。
                                        //否则有个白底在那儿，你的dialog也是白色的话是看不到圆角的
                                        window.setBackgroundDrawableResource(android.R.color.transparent);
                                    }
                                }


                                break;
                            case AppContent.yourlocation:
                                //todo 点击了我的位置的describe

                                break;
                            case AppContent.cat:
                                //todo 在流浪猫中点击了desceibe
                                //对经纬度进行比对
                                mlatitude = marker.getPosition().latitude;
                                mlongtitude = marker.getPosition().longitude;
                                for(CatWitness c:cl){
                                    //匹配坐标点
                                    if((c.getLatitude()+"").substring(0,7).equals((mlatitude+"").substring(0,7)) &&
                                            (c.getLongtitude()+"").substring(0,7).equals((mlongtitude+"").substring(0,7))){
                                        //匹配成功
                                        //弹出窗口
                                        Cat_Detial_Dialog dialog = new Cat_Detial_Dialog.Builder(getContext()).sethealth(c.getCatHealth())
                                                .sethospital(c.getCatHospital()).settype(c.getCattype()).create();
                                        dialog.show();
                                        Window window = dialog.getWindow();
                                        //如果你是圆角之类的话，这句设置背景透明要加上。
                                        //否则有个白底在那儿，你的dialog也是白色的话是看不到圆角的
                                        window.setBackgroundDrawableResource(android.R.color.transparent);
                                    }
                                }
                                break;
                            case AppContent.clothes:
                                //todo 在衣服捐赠中点击了describe
                                //对经纬度进行比对
                                mlatitude = marker.getPosition().latitude;
                                mlongtitude = marker.getPosition().longitude;
                                for(ClothesDonation cd:cdl){
                                    //匹配坐标点
                                    if((cd.getLatitude()+"").substring(0,7).equals((mlatitude+"").substring(0,7)) &&
                                            (cd.getLongtitude()+"").substring(0,7).equals((mlongtitude+"").substring(0,7))) {
                                        //匹配成功，弹出窗口
                                        Clothes_Donation_Detial_Dialog dialog_clothes =
                                                new Clothes_Donation_Detial_Dialog.Builder(getContext())
                                                .setdescribe(cd.getCDDescription())
                                                .settype(cd.getCDName())
                                                .create();
                                        dialog_clothes.show();;
                                        Window window = dialog_clothes.getWindow();
                                        //如果你是圆角之类的话，这句设置背景透明要加上。
                                        //否则有个白底在那儿，你的dialog也是白色的话是看不到圆角的
                                        window.setBackgroundDrawableResource(android.R.color.transparent);

                                    }

                                    }
                                break;
                        }

                        break;
                }
            }
        };
        switch (marker.getTitle()){
            case AppContent.yourlocation:
                //todo 点击了我的位置
                Log.i("marker","我的位置");

                break;
            case AppContent.libaray:

                //todo 点击了一个图书馆
                SelectPicPopupWindow window = new SelectPicPopupWindow(getActivity(), dialoglistener);
                //显示窗口
                window.showAtLocation(getActivity().findViewById(R.id.meButton),
                        Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
                break;
            case AppContent.cat:
                //todo 点击了流浪猫
                CatSelectPicPopupWindow window_cat = new CatSelectPicPopupWindow(getActivity(),dialoglistener);
                //显示窗口
                window_cat.showAtLocation(getActivity().findViewById(R.id.meButton),
                        Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
                break;
            case AppContent.clothes:
                //todo 点击了捐衣活动
                ClothesDonationSelectPicPopupWindow window_clo = new ClothesDonationSelectPicPopupWindow(getActivity(),dialoglistener);
                //显示窗口
                window_clo.showAtLocation(getActivity().findViewById(R.id.meButton),
                        Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
                break;
                default:
                    //todo 点击了其他标点
                    Log.i("marker","其他点");

                    window = new SelectPicPopupWindow(getActivity(), dialoglistener);
                    //显示窗口
                    window.showAtLocation(getActivity().findViewById(R.id.meButton),
                            Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);

                    break;
        }
        return false;
    }





}

